/*
 * Copyright (c) 2010 CCX(China) Co.,Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * CCX(China) Co.,Ltd. ("Confidential Information").
 * It may not be copied or reproduced in any manner without the express 
 * written permission of CCX(China) Co.,Ltd.
 *
 * Author: zhnb
 * Date: 2011-6-3 下午02:45:23
 */
package com.telnet;

import java.io.IOException;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Set;

/**
 * 使用socket方式扫描商品
 * @author zhnb
 *
 */
public class ScannerBySocket implements Runnable, Serializable {

    private static final long serialVersionUID = -5241137618232466038L;
    
    private InetAddress inetAddress;
    private int port;
    private int timeout;
    
    // 存储扫描已返回成功信息的端口
    protected static Set<Object> ports = new HashSet<Object>();
    
    /**
     * 创建扫描执行者
     * @param ipAddress     IP地址
     * @param port          端口
     * @param timeout       超时（毫秒）
     */
    public ScannerBySocket(String ipAddress, int port, int timeout){
        try {
            inetAddress = InetAddress.getByName(ipAddress);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        this.port = port;
        this.timeout = timeout;
    }

    @Override
    public void run() {
        
        Socket socket = null;
        
        try {
            
            socket = new Socket();
            socket.connect(new InetSocketAddress(inetAddress, this.port), this.timeout);
            
            ports.add(this.port);
            System.out.println(port+": "+socket.isConnected());
            
        } catch (IOException e) {
            //System.out.println(this.port + " IO Faild.");
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                //System.out.println(Thread.currentThread().getName() + " \t: " + this.port + " CL Faild.");
            }
        }
        
    }
    
    /**
     * 获取当前扫描集信息
     * @return
     */
    protected static String getInfo(){
        
        StringBuffer buffer = new StringBuffer();
        
        // 复制当前扫描成功的端口集
        Set<Object> tempPorts = new HashSet<Object>();
        tempPorts.addAll(ports);
        
        for (Object obj : tempPorts) {
            buffer.append( "|" + ((obj == null)? null : obj.toString()) );
        }
        
        return buffer.toString();
    }

}
